import React, { PureComponent } from 'react';
import {Icon, Modal, Tabs, Radio, Pagination, Button, Spin, message } from 'antd';
import styles from '../index.less';

import {EmptyVideo, VideoItem} from '../common'
const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;

export default class ListModal extends PureComponent {
  constructor(props) {
    super(props);
    this.nicaiCrx = document.getElementById('nicaiCrx');
    this.state = {
      version: '',
      videoList: [],
      total: 0,
      addModalVisible: false,
      activeKey: '1'
    }
  }

  componentDidMount() {
  }
  componentWillReceiveProps(nextProps) {
    if(!this.props.visible && nextProps.visible) {
      this.nicaiCrx.addEventListener('setMaterial', this.setMaterial);
      let type = this.props.enableInteractVideo ? 'ivideo' : 'video'
      this.handleGetMaterial({type: type, current: 1, pageSize: 20});
      let activeKey = this.props.enableInteractVideo ? '1' : '2'
      this.setState({activeKey: activeKey})
    } else if (this.props.visible && !nextProps.visible) {
      this.nicaiCrx.removeEventListener('setVersion', this.setVersion);
      this.nicaiCrx.removeEventListener('setMaterial', this.setMaterial);
    }
  }

  setMaterial = (e) => {
    const res = JSON.parse(e.target.innerText);
    if(res.status === 'SUCCESS'){
      let {current, total, itemList} = res.data
      this.setState({
        videoList: itemList,
        total: total,
        currentPage: current,
      })
    } else {
      if(res.status === 'NOT_LOGIN') {
        message.warn('淘宝登录失效，请重新登录淘宝');
      } else {
        message.warn(res);
      }
    }
  }

  setVersion = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.version) {
      this.setState({version: data.version,});
    }
    if (data.error) {
      message.warn(data.msg);
    }
  }

  handleRequestNicaiCrx = (params) => {
    this.nicaiCrx.innerText = JSON.stringify(params);
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('taobaoRequest', true, true);
    this.nicaiCrx.dispatchEvent(customEvent);
  }


  handleGetMaterial = (params) => {
    let {type, current, pageSize} = params
    this.handleRequestNicaiCrx({
      url: 'https://resource.taobao.com/video/getMaterial',
      type: 'GET',
      data: {
        type,
        current,
        pageSize,
        vf: 'p',
        producerSource: 1
      },
      actionName: 'setMaterial',
    })
  }
  handleTabChange = key => {
    let type = ['ivideo', 'video'];
    this.setState({videoList: []})
    this.handleGetMaterial({type: type[key-1], current: 1, pageSize: 20});
    this.props.onVideoRadioChange('')
    this.setState({activeKey: key})
  }

  onPageChange = (pageNumber, type) => {
    this.handleGetMaterial({type: type,current: pageNumber, pageSize: 20});
  }
  onVideoRadioChange = (e) => {
    this.props.onVideoRadioChange(e.target.value)
  }

  render() {
    let {
      visible, enableInteractVideo, enableNormalVideo, filterDurGreater, filterDurLess,
      handleOk, handleCancel, onVideoRadioChange,
    } = this.props
    let {videoList, total, currentPage,} = this.state
    return (
      <div>
        <Modal
          title="添加视频"
          width="850px"
          visible={visible}
          onOk={handleOk}
          onCancel={handleCancel}
          style={{ top: 30 }}
          bodyStyle={{ padding: '5px 20px' }}
          footer={[
            <Button key="submit" disabled={this.props.selectVideo === ''} type="primary" onClick={() => handleOk(this.props.selectVideo)}>
              确认
            </Button>,
            <Button key="back" onClick={handleCancel}>取消</Button>,
          ]}
        >

          <Tabs activeKey={this.state.activeKey} onChange={this.handleTabChange}>
            {enableInteractVideo &&
              <TabPane tab="添加互动视频" key="1">
                <div>互动视频可以在视频中加入宝贝等互动玩法哦~ 请选择已编辑的互动视频</div>
                <div className={styles['video-list']}>
                    <RadioGroup onChange={this.onVideoRadioChange} value={this.props.selectVideo}
                      style={{display: 'flex',flexWrap: 'wrap'}}
                    >
                    <EmptyVideo label={'创建互动视频'}
                      height='210px'
                      width='248px'
                      handleClick={() => {window.open('https://we.taobao.com/material/mine/video? type=ivideo&showDialog=createInteractiveVideo')}}
                    />
                      {videoList.map((item, idx) =>
                        <VideoItem {...item} key={`VideoItem4567${idx}`}
                          filterDurGreater={filterDurGreater} filterDurLess={filterDurLess}
                          onVisit={() => this.props.onVisit(item)}
                        >
                          {item.ratio !== 'N/A' &&
                          <Radio key={item.interactId} value={item} className={styles['radio']}>
                            <span style={{
                              width: 248,
                              height: 49,
                              position: 'absolute',
                              bottom: -16,
                              right: 1,
                            }}></span>
                          </Radio>}
                        </VideoItem>
                      )}
                    </RadioGroup>
                </div>
                <Pagination defaultCurrent={currentPage} defaultPageSize={20} total={total} style={{marginTop: 10}} onChange={(pageNumber) => this.onPageChange(pageNumber, 'ivideo')}/>
              </TabPane>
            }


            {enableNormalVideo &&
              <TabPane tab="添加普通视频" key="2">
                <div>请选择视频
                  <span style={{color: 'rgb(153, 153, 153)'}} >(仅显示转码完成的视频)</span>
                </div>
                <div className={styles['video-list']}>
                  <RadioGroup onChange={this.onVideoRadioChange} value={this.props.selectVideo}
                      style={{display: 'flex',flexWrap: 'wrap'}}
                    >
                    <EmptyVideo label={'上传普通视频'}
                      height='210px'
                      width='248px'
                      handleClick={() => {
                        window.open('https://we.taobao.com/material/mine/video?type=ivideo&showDialog=uploadVideo')
                      }
                    } />
                    {videoList.map((item,idx) =>
                        <VideoItem {...item} key={idx}
                          onVisit={() => this.props.onVisit(item)}
                          filterDurGreater={filterDurGreater} filterDurLess={filterDurLess}
                        >
                          {item.ratio !== 'N/A' &&
                          <Radio key={idx} value={item} className={styles['radio']}>
                            <span style={{
                              width: 248,
                              height: 49,
                              position: 'absolute',
                              bottom: -16,
                              right: 1,
                            }}></span>
                          </Radio>}
                        </VideoItem>
                      )}
                  </RadioGroup>
                </div>
                <Pagination defaultCurrent={currentPage} defaultPageSize={20} total={total} style={{marginTop: 10}} onChange={(pageNumber) => this.onPageChange(pageNumber, 'video')}/>
              </TabPane>
            }
          </Tabs>
        </Modal>
      </div>
    )
  }
}
